<template>
  <div class="wrapper-edit">
    <div class="wrapper-form">
      <el-form ref="refForm" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="所属栏目">
          <el-tree-select
            v-model="formData.idCategory"
            :data="treeSelectData"
            :props="{ value: 'id', label: 'title' }"
            :render-after-expand="false"
            :current-node-key="0"
            value-key="id"
            placeholder="选择所属栏目"
            check-strictly
          />
        </el-form-item>

        <el-form-item label="文章属性">
          <el-checkbox-group v-model="symbolShows" @change="onSymbolShowChange">
            <el-checkbox v-for="item in symbolShowOptions" :key="item.id" :label="item.id">
              {{ item.lable }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="跳转链接">
          <el-input ref="refJumpUrl" v-model="formData.urlJump" maxlength="300" show-word-limit />
        </el-form-item>

        <el-form-item label="标签">
          <el-input v-model="formData.tag" maxlength="100" placeholder="多个标签以半角英文 , 分隔" />
        </el-form-item>

        <el-form-item label="主标题" prop="title">
          <el-input v-model="formData.title" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="短标题">
          <el-input v-model="formData.titleShort" maxlength="20" show-word-limit />
        </el-form-item>

        <el-form-item label="引题">
          <el-input v-model="formData.titleHead" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="副标题">
          <el-input v-model="formData.titleSub" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="标题图">
          <TheUploaderImage :selectedFile="titlePicList" @setUploadResult="getUploadResult" />
        </el-form-item>

        <el-form-item label="正文内容">
          <Tinymce6 :content="formData.content" @inputContent="getContent" />
        </el-form-item>

        <el-form-item label="文章简介">
          <el-input v-model="formData.intro" :rows="6" type="textarea" maxlength="140" show-word-limit />
        </el-form-item>

        <el-form-item label="来源">
          <el-input v-model="formData.source" maxlength="30" placeholder="例：新华社微信公众号" />
        </el-form-item>

        <el-form-item label="作者">
          <el-input v-model="formData.author" maxlength="20" />
        </el-form-item>

        <el-form-item label="点击次数">
          <el-input-number v-model="formData.click" :min="1" :max="99999999" />
        </el-form-item>

        <el-form-item label="发布时间">
          <el-date-picker
            v-model="formData.dtPublish"
            type="datetime"
            placeholder="选择文章发布日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onUpdate">确定修改</el-button>
          <el-button @click="onBack2List">取消并返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getAdminId } from '@/utils/common'
import { obj2Str } from '@/utils/datetime'
import { AryToTree, IsAryContainVal } from '@/utils/array'
import { toastSuccess, toastError } from '@/utils/toast'
import { getSStorageObj, getLStorageObj } from '@/utils/web-storage'

import Tinymce6 from '@c/Tinymce6'
import TheUploaderImage from '@c/UploadImage2Local'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'ArticleEditView',
  components: { Tinymce6, TheUploaderImage },
  setup() {
    const idAdmin = ref(0)
    const formData = ref({
      id: 0,
      idCategory: 228,
      symbolShow: '',
      source: '',
      status: '0',
      author: '',
      idEditor: 0,
      idChecker: 0,
      idSigner: 0,
      tag: '',
      title: '',
      titleHead: '',
      titleSub: '',
      titleShort: '',
      // 标题图不仅仅有图像的 url ，还有 uuid，因此这里存的是一个对象
      urlTitlePic: '',
      urlTitleVideo: '',
      urlJump: '',
      content: '',
      intro: '',
      dtCreate: obj2Str(new Date()),
      dtPublish: obj2Str(new Date()),
      flagDeleted: 0,
      sort: 1,
      idZone: 1,
      click: 0,
    })
    const rules = ref({
      title: [
        { required: true, message: '标题不能为空！', trigger: 'blur' },
        { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' },
      ],
    })
    const symbolShows = ref([])
    const symbolShowOptions = ref([
      { id: 'a', lable: '特荐' },
      { id: 'b', lable: '加粗' },
      { id: 'c', lable: '推荐' },
      { id: 'f', lable: '幻灯' },
      { id: 'h', lable: '头条' },
      { id: 'j', lable: '跳转' },
      { id: 'p', lable: '图片' },
      { id: 's', lable: '滚动' },
    ])
    const treeSelectData = ref([])
    const titlePicList = ref([])
    const refForm = ref(null)
    const refJumpUrl = ref(null)

    const getIdAdmin = () => {
      idAdmin.value = getAdminId()
    }
    const onBack2List = () => {
      // router.push({ path: 'list-page' })
      router.go(-1)
    }
    // 得到所有文章分类
    const listCategory = () => {
      treeSelectData.value = AryToTree(getLStorageObj('AllCategory'), 228)
    }
    // 获取传参文章
    const getQuery = () => {
      const article = getSStorageObj('ParamData')
      if (!article) onBack2List()
      console.log('article', article)
      // 设置文章表单
      formData.value.id = article.id
      formData.value.idCategory = parseInt(article.IdCategory)
      if (article.SymbolShow && article.SymbolShow !== '') {
        symbolShows.value = article.SymbolShow.split(',')
      }
      formData.value.source = article.Source
      formData.value.status = article.Status
      formData.value.author = article.Author
      formData.value.tag = article.Tag
      formData.value.title = article.Title
      formData.value.titleHead = article.TitleHead
      formData.value.titleSub = article.TitleSub
      formData.value.titleShort = article.TitleShort
      // 设置标题图
      formData.value.urlTitlePic = article.UrlTitlePic
      if (article.UrlTitlePic) {
        titlePicList.value.push(JSON.parse(article.UrlTitlePic))
      } else {
        titlePicList.value = []
      }
      formData.value.urlTitleVideo = article.UrlTitleVideo
      formData.value.urlJump = article.UrlJump
      formData.value.content = article.Content
      formData.value.intro = article.Intro
      formData.value.dtCreate = article.DtCreate
      formData.value.dtPublish = article.DtPublish
      formData.value.flagDeleted = article.FlagDeleted
      formData.value.idEditor = article.IdAdmin
      formData.value.idChecker = article.IdChecker
      formData.value.idSigner = article.IdSigner
      formData.value.sort = article.Sort
      formData.value.click = article.Click
    }
    // 设置文章属性复选框的值发生变化时
    const onSymbolShowChange = (val) => {
      // console.log('onSymbolShowChange val:', val)
      // 如果填了跳转链接，则 refJumpUrl 的内容为空
      if (val.indexOf('j') >= 0) {
        refJumpUrl.value.focus()
      } else {
        formData.value.urlJump = ''
      }
    }
    // 设置标题图url
    const getUploadResult = (val) => {
      if (val && val !== '') {
        formData.value.urlTitlePic = JSON.stringify(val)
      } else {
        formData.value.urlTitlePic = ''
      }
    }
    // 获取tinymce内容
    const getContent = (val) => {
      formData.value.content = val
    }
    const onUpdate = () => {
      // 检查栏目
      if (formData.value.idCategory <= 228) {
        toastError('请选择文章所属栏目')
        return false
      }
      // 检查跳转链接
      if (IsAryContainVal(symbolShows.value, 'j')) {
        if (formData.value.urlJump === '') {
          toastError('请设置跳转链接！')
          refJumpUrl.value.focus()
          return false
        }
      }
      formData.value.symbolShow = symbolShows.value.join(',')
      // 先验证表单
      refForm.value.validate((valid) => {
        if (!valid) {
          toastError('表单验证未通过！请检查您的输入！')
          return false
        }
        // 通过验证，提交给后台
        store
          .dispatch('article/modifyAll', formData.value)
          .then(() => {
            toastSuccess('修改文章成功！')
            router.go(-1)
          })
          .catch((error) => {
            toastError('服务器修改文章返回错误：' + error)
          })
      })
    }

    onMounted(() => {
      getIdAdmin()
      listCategory()
      getQuery()
    })

    return {
      idAdmin,
      formData,
      rules,
      symbolShows,
      symbolShowOptions,
      treeSelectData,
      titlePicList,
      refForm,
      refJumpUrl,
      getIdAdmin,
      getQuery,
      onBack2List,
      listCategory,
      onSymbolShowChange,
      getUploadResult,
      getContent,
      onUpdate,
    }
  },
})
</script>

<style lang="scss" scoped></style>
